import React, { Component } from 'react';
import Taro from '@tarojs/taro';
import {Block, Button, Image, Navigator, Text, View} from '@tarojs/components'
import {AtIcon} from 'taro-ui'
import {user} from '../../utils/user.service'
import {http} from '../../utils/http'
import {IDENTITY, REDBAG_GET_V3, RESOURCE_URL, SCAN_BIND_SELLER, UPDATE_USER_SHARE_DATE} from '../../constants/api'
import {UserIdentity} from "../../utils/server.interface";
import {platform} from "../../utils/platform-settting.service";
import {GetRequest, getTempSellerId, vcmonitor} from "../../utils/tools";
import {h5Wx} from "../../utils/h5.service";
import GzhAuth from "../../components/gzh-auth/gzh-auth"
import './help.scss'

export default class Help extends Component {
  state: {
    sellerId: string
    userId: string
    nickName: string
    bId: number
    redbag: number
    isLogin: boolean
    show: boolean
  } = {
    sellerId: '',
    userId: '',
    nickName: '',
    bId: 0,
    redbag: 0,
    isLogin: false,
    show: false,
  }

  shareParams = ''

  async UNSAFE_componentWillMount() {
    if (process.env.TARO_ENV === 'h5') {
      await h5Wx.getConfig()
    }
    vcmonitor(this)
  }

  async componentDidShow() {
    const isLogin = await user.checkLogin()
    if (!isLogin) {
      Taro.showToast({
        title: '你还未登录，请登录',
        icon: 'none',
      })
      const timer = setTimeout(() => {
        clearTimeout(timer)
        user.jumpLogin()
      }, 1000)
      return
    }
    let platformSet = platform.info
    if (!platform.isLoaded) {
      platformSet = (await platform.getSetting()) || platform.info
    }
    const bindSellerId = Taro.getStorageSync('bindSellerId') || 0;
    let bSellerId = Taro.getCurrentInstance().router.params.sellerId || 0
    const parentBid = Taro.getCurrentInstance().router.params.bId || 0
    const parentUserId = Taro.getCurrentInstance().router.params.userId || ''
    if (platformSet.isSellerPermanentLock) {
      if (bindSellerId) {
        bSellerId = bindSellerId
      }
      Taro.setStorageSync('bindSellerId', bSellerId)
    }
    Taro.showLoading({title: '加载中'})
    this.shareParams = await user.getSellerParams(getTempSellerId(this))
    if (isLogin) {
      const identity = await http.get<UserIdentity>(IDENTITY, {});
      this.setState({
        userId: identity.userId,
        sellerId: identity.sellerId,
        bId: this.randomNumber(),
        isLogin
      }, async () => {
        this.setState({nickName: identity.nickname || '',})
        const redbag = await this.getRedbag(parentBid, bSellerId, parentUserId)
        if (redbag) {
          this.setState({redbag})
        }
      })
      if (process.env.TARO_ENV === 'h5') {
        const shareData = {
          title: platform.info.platformName,
          desc: "在吗？世界这么大，一起去看看，给你发红包了，记得领啊！",
          link: window.location.origin + '/common/redbag/help?userId=' + identity.userId + '&sellerId=' + identity.sellerId + '&bId=' + this.randomNumber() + `&${this.shareParams}`,
          imgUrl: RESOURCE_URL + '/resources/images/share_card.png'
        }
        h5Wx.share(shareData)
      }
    }

    const bindSellerIds = Taro.getCurrentInstance().router.params.bindSellerId || ''
    const tempSellerIds = Taro.getCurrentInstance().router.params.tempSellerId || ''
    if ((bindSellerIds || tempSellerIds) && process.env.DISTINGUISH_IDENTITY) {
      http.HPost(SCAN_BIND_SELLER, { temp_seller_id: tempSellerIds, refer_seller_id: bindSellerIds });
    }
    Taro.hideLoading()
  }

  async getRedbag(parentBid, sellerId, parentUserId) {
    if (sellerId == undefined) {
      sellerId = 0
    }
    return await http.post<number>(REDBAG_GET_V3, {
      'bId': this.state.bId,
      'parentBId': parentBid,
      'sellerId': sellerId,
      'parentUserId': parentUserId
    })
  }

  onShareAppMessage() {
    if (process.env.TARO_ENV !== 'tt') {
      http.post(UPDATE_USER_SHARE_DATE, {})
    }
    return {
      title: this.state.nickName + ":在吗？世界这么大，一起去看看，给你发红包了，记得领啊！",
      path: '/common/redbag/help?userId=' + this.state.userId + '&sellerId=' + this.state.sellerId + '&bId=' + this.randomNumber() + `&${this.shareParams}` + `&sKey=${Taro.getStorageSync('sKey' || '')}`,
      imageUrl: RESOURCE_URL + '/resources/images/share_card.png',
    }
  }

  randomNumber() {
    const now = new Date()
    const month = now.getMonth() + 1
    const day = now.getDate()
    const hour = now.getHours()
    const minutes = now.getMinutes()
    const seconds = now.getSeconds()
    return now.getFullYear().toString() + month.toString() + day + hour + minutes + seconds + (Math.round(Math.random() * 89 + 100)).toString()
  }

  async login() {
    await user.jumpLogin()
  }

  jump(path) {
    Taro.switchTab({url: path})
  }

  shareWow() {
    const show = this.state.show
    this.setState({
      show: !show
    })
  }

  render() {
    const {redbag, isLogin, show} = this.state
    return (
      <View className='helpRoot'>
        <GzhAuth />
        <View className='page-bd'>
          <Image className='bgimg' mode='widthFix'
            src='https://resource.ivcheng.com/upload/images/20211016/1634361869049_827.png'
          />
          <View className='content-box'>
            <View className='common_text'>通用抵扣红包</View>
            <View className='common_tips'>邀请好友助力，红包会变大哦</View>
            <View className='price_box'>
              <Text className='price'>{redbag}</Text>
              <Text className='yuan'>元</Text>
            </View>
            <View onClick={this.jump.bind(this, '/pages/index/index')} className='use'>已存入我的红包里，可去使用 <AtIcon
              value='chevron-right' size='18' color='#c69a52'
            /></View>
            <View className='btn-con'>
              {process.env.TARO_ENV != 'h5' ?
                <Block>
                  {!isLogin && <Button className='btn btn1' onClick={this.login.bind(this)}>邀请好友助力</Button>}
                  {isLogin && <Button className='btn btn1' openType='share'>邀请好友助力</Button>}
                </Block>
                :
                <Block>
                  {!isLogin && <Button className='btn btn1 h5-btn' onClick={this.login.bind(this)}>邀请好友助力</Button>}
                  {isLogin && <Button className='btn btn1 h5-btn' onClick={this.shareWow.bind(this)}>邀请好友助力</Button>}
                  {show && <View className='H5shareBox' onClick={this.shareWow.bind(this)}>
                    <Image className='H5shareImg' src='https://resource.ivcheng.com/resources/images/H5sharebj.png'
                      mode='widthFix'
                    />
                    <View className='H5shareBtn'>我知道了</View>
                  </View>}
                </Block>
              }
              <Navigator className='btn btn2' url='/pages/index/index' openType='switchTab'>使用红包支付</Navigator>
            </View>
          </View>
        </View>
      </View>
    )
  }
}
